package com.fearless.test20210503.forkjoin;
/*

    计算1到10亿的和。查看三种程序员不同的运算方式，以及分别所花费时间

 */


import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class Test1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        test01();
        test02();
        test03();

    }

//普通程序员
    public static void test01(){
        long start=System.currentTimeMillis();
        long sum=0;

        for (long i = 1L; i <=10_0000_0000 ; i++) {
            sum+=i;
        }
        long end=System.currentTimeMillis();

        System.out.println("普通程序员。计算结果是"+sum+"花费时间是"+(end-start));

    }

//中级程序员
    public static void test02() throws ExecutionException, InterruptedException {
        Long start=System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();

        ForkJoinTask<Long> task = new ForkJoinDemo(1L, 10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);//提交任务
        Long aLong = submit.get();//获取返回值

        Long end=System.currentTimeMillis();

        System.out.println("中级程序员。计算结果是"+aLong+"花费时间是"+(end-start));

    }



//高级程序员
    public static void test03(){
//使用并行流
        Long start=System.currentTimeMillis();

        long sum = LongStream.rangeClosed(1L, 10_0000_0000L).parallel().reduce(0,Long::sum);


        long end=System.currentTimeMillis();

        System.out.println("高级程序员。计算结果是"+sum+"花费时间是"+(end-start));


    }




}
